//
// Created by denglibin on 19-10-29.
//
/**
 *udp组播（多播）
 **/
#include <stdio.h>
#include <sys/socket.h>
#include <ctype.h>
#include <strings.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <string.h>
#include <unistd.h>
#define SERVER_PORT 8000
#define CLIENT_PORT 9000
#define MAX_LINE 1024
#define GROUP "239.0.0.2" //组播地址 239开头 任意 (组名)

static int main_(void){

    int sock_fd;
    struct sockaddr_in server_addr, client_addr;
    struct ip_mreqn group;
    char buf[MAX_LINE] = "hello everyone";

    /*构造用于udp通信的套接字*/
    sock_fd = socket(AF_INET, SOCK_DGRAM, 0);

    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;/*IP V4*/
    server_addr.sin_port = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);/*任意ip*/

    bind(sock_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));

    /*设置组地址*/
    inet_pton(AF_INET, GROUP, &group.imr_multiaddr);
    /*本地任意ip*/
    inet_pton(AF_INET, "0.0.0.0", &group.imr_address);
    group.imr_ifindex = 3; //网卡编号  ip ad 命令  3: wlp6s0
    //group.imr_ifindex = if_nametoindex("wlp6s0");

    /*设置socket选项, 让socket具备组播能力*/
    setsockopt(sock_fd, IPPROTO_IP, IP_MULTICAST_IF, &group, sizeof(group));

    /*构造客户端ip 端口*/
    bzero(&client_addr, sizeof(client_addr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(CLIENT_PORT);
    inet_pton(AF_INET, GROUP, &client_addr.sin_addr.s_addr);

    /*发送数据包*/
    while (1){
        printf("send...\n");
        sendto(sock_fd, buf, strlen(buf), 0, (struct sockaddr*)&client_addr, sizeof(client_addr));
        sleep(1);
    }
    return 0;
}


